// pages/contens/contens.js
let db = wx.cloud.database()
let app = getApp()
let id = app.globalData.openid
Page({

    /**
     * 页面的初始数据
     */
    data: {
        input: false,
        comment: "",
        defaultAvatar: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
        actions: [
            {name: '回复',},
            {name: '复制',},
            {name: '删除',},
          ],
        selectCommentIndex: -1
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        let that = this
        const eventChannel = this.getOpenerEventChannel()
        eventChannel.on('acceptDataFromOpenerPage',(e)=>{
            let id = e.id
            that.setData({id})
            db.collection('articleDB').doc(id).get({
                success: (res) => {           
                  console.log(res);
                    that.setData({
                        image: res.data.imageList,
                        title: res.data.title,
                        article: res.data.article,
                        area: res.data.area,
                        authorID: res.data._openid
                    })

                    // 点赞和收藏和关注
                    let like = res.data.like
                    if ( app.globalData.openid in like ) {
                        that.setData({like: true})
                    } else {
                        that.setData({like: false})
                    }
                    that.setData({likeNumber: Object.keys(like).length})

                    let favourite = res.data.favourite
                    if ( app.globalData.openid in favourite ) {
                        that.setData({favourite: true})
                    } else {
                        that.setData({favourite: false})
                    }
                    that.setData({favouriteNumber: Object.keys(favourite).length})

                    let authorID = res.data._openid
                    db.collection('userDB').where({
                        _openid: app.globalData.openid
                    }).get({
                        success: (res) => {
                            let follows = res.data[0].follow
                            if (authorID in follows) {
                                that.setData({follow: true})
                            } else {
                                that.setData({follow: false})
                            }
                        }
                    })

                    // 作者信息
                    db.collection('userDB').where({
                        _openid: res.data._openid
                    }).get({
                        success: (res) => {
                            that.setData({
                                avatar: res.data[0].avatar,
                                nickname: res.data[0].nickname
                            })
                        }
                    })
                    that.getComment()
                }
            })
        })
    },
    showComment() {
        this.setData({input: true, selectCommentIndex: -1, placeholder: "", fatherIndex: "", target: ""})
    },
    onClose() {
        this.setData({input: false,select: false})
    },
    addComment() {
        let that = this
        let content = {"openid":app.globalData.openid,"content":this.data.comment,"like":{},createTime:db.serverDate(),comment:[]};
        let index = this.data.selectCommentIndex
        let fatherIndex = this.data.fatherIndex
        if (this.data.comment.length == 0) {
            return
        }
        wx.cloud.callFunction({
            name: 'checkContent',
            data: {
                content: this.data.comment
            },
            success: (res) => {
                let suggest = res.result.result.suggest // 审核建议
                let label = res.result.result.label // 退回原因
                // 100 正常；10001 广告；20001 时政；20002 色情；20003 辱骂；20006 违法犯罪；20008 欺诈；20012 低俗；20013 版权；21000 其他
                console.log();
                let reason = {'10001': '广告','20001': '时政','20002': '色情','20003': '辱骂','20006': '犯罪','20008': '欺诈','20012': '低俗','20013': '版权','21000': '不良'}
                if (suggest != 'pass') {
                    wx.showModal({
                        title: "言论不当！",
                        content: `可能涉及${reason[label]}内容，请修改后再发吧！`,
                        showCancel: false,
                        confirmText: '知道啦',
                        confirmColor: '#f17700'
                    })
                } else {
                    // 如果不是回复评论
                    if (index == -1) {
                        db.collection('articleDB').doc(this.data.id).update({
                            data: {
                                comment: db.command.unshift([content])
                            },
                            success: (res) => {
                                that.onClose()
                                that.setData({comment: ""})
                                that.getComment();
                            }
                        })
                    } else {
                        // 如果是回复评论
                        content = {"openid":app.globalData.openid,"content":this.data.comment,"like":{},createTime:db.serverDate(),comment:[], target: this.data.target};
                        db.collection('articleDB').doc(this.data.id).update({
                            data: {
                                [`comment.${fatherIndex}.comment`]: db.command.unshift([content])
                            },  
                            success: function(res) {
                                that.onClose()
                                that.setData({comment: ""})
                                that.getComment();
                            }
                        })
                    }
                }
            }
        })
    },
    getComment() {
        let that = this
        db.collection("articleDB").doc(this.data.id).get({
            success: (res) => {
                this.setData({commentArr: res.data.comment})
                for (let i in res.data.comment) {
                    let comment = res.data.comment[i]
                    db.collection("userDB").where({
                        _openid: comment.openid
                    }).get({
                        success: (res) => {
                            comment['avatar'] = res.data[0].avatar
                            comment['nickname'] = res.data[0].nickname
                            that.setData({['commentArr['+i+']']: comment})
                        }
                    })
                    // 评中评
                    for (let j in res.data.comment[i].comment) {
                        let comment = res.data.comment[i].comment[j]
                        db.collection("userDB").where({
                            _openid: comment.openid
                        }).get({
                            success: (res) => {
                                comment['avatar'] = res.data[0].avatar
                                comment['nickname'] = res.data[0].nickname
                                that.setData({['commentArr['+i+'].comment['+j+']']: comment})
                            }
                        })
                    }
                }
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },
    likeIt() {
        let that = this
        if (this.data.like == false) {
            this.setData({like: true,likeNumber: this.data.likeNumber + 1})
            db.collection('articleDB').doc(this.data.id).update({
                data: {
                    [`like.${app.globalData.openid}`]: "like it!"
                }
            })
        } else {
            this.setData({like: false, likeNumber: this.data.likeNumber - 1})
            db.collection('articleDB').doc(this.data.id).update({
                data: {
                    [`like.${app.globalData.openid}`]: db.command.remove()
                }
            })
        }
    },
    favouriteIt() {
        let that = this
        if (this.data.favourite == false) {
            this.setData({favourite: true,favouriteNumber: this.data.favouriteNumber + 1})
            db.collection('articleDB').doc(this.data.id).update({
                data: {
                    [`favourite.${app.globalData.openid}`]: "favourite it!"
                }
            })
            db.collection('userDB').where({
                _openid: app.globalData.openid
            }).update({
                data: {
                    [`favourite.article.${that.data.id}`]: "favourite it!"
                }
            }) 
        } else {
            this.setData({favourite: false, favouriteNumber: this.data.favouriteNumber - 1})
            db.collection('articleDB').doc(this.data.id).get({
                success: function(res) {
                    let favourite = res.data.favourite
                    delete favourite[app.globalData.openid]
                    db.collection('articleDB').doc(that.data.id).update({
                        data: {
                            favourite: db.command.set(favourite)
                        }
                    })
                }
            })
            db.collection('userDB').where({
                _openid: app.globalData.openid
            }).update({
                data: {
                    [`favourite.article.${that.data.id}`]: db.command.remove()
                }
            })
        }
    },
    followIt() {
        let that = this
        if (this.data.follow == false) {
            this.setData({follow: true})
            db.collection('userDB').where({
                _openid: app.globalData.openid
            }).update({
                data: {
                    [`follow.${that.data.authorID}`]: "follow it!"
                }
            }) 
        } else {
            this.setData({follow: false})
            db.collection('userDB').where({
                _openid: app.globalData.openid
            }).update({
                data: {
                    [`follow.${that.data.authorID}`]: db.command.remove()
                }
            })
        }
    },
    lookImage(e){
        let current = this.data.image[e.currentTarget.dataset.index];
        wx.previewImage({
            urls: this.data.image,
            current: current
        })
    },
    selectComment(e) {
        console.log(e);
        let index = e.currentTarget.dataset.index
        let type = e.currentTarget.dataset.type
        this.setData({select: true, selectCommentIndex: index, fatherIndex: e.mark.index, target: e.currentTarget.dataset.target, type: type, selectComment: '@' + e.currentTarget.dataset.nickname + '：' + e.currentTarget.dataset.content})
    },
    onSelect(e) {
        console.log(e);
        let name = e.detail.name
        let index = this.data.selectCommentIndex
        let nickname = this.data.commentArr[index].nickname
        if (this.data.type == "subcomment") {
            let fatherIndex = this.data.fatherIndex
            nickname = this.data.commentArr[fatherIndex].comment[index].nickname
        }
        if (name == "回复") {
            setTimeout(()=>{
                this.setData({input: true,placeholder: "回复@" + nickname + "："})
            },300)
        } else if (name == "复制") {
            let content = this.data.commentArr[index].content
            wx.setClipboardData({data: content})
        } else if (name == "删除") {
            this.onClose()
        }
    },
    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    }
})